﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using HiTeachers.Entities;
using HiTeachers.Services;
using HiTeachers.Services.Exceptions;
using HiTeachers.Utilities;

namespace HiTeachers.Web
{
    public partial class PostRequest : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;

            BindingSubject(chklSubject);
            Page.CloseMessage(lblMsg);

            BindingMetaData("PostRequest");
            var siteConfig = SiteConfigServices.GetByTextKey("PostRequest");
            if (siteConfig != null) Page.Title = siteConfig.Value;
        }

        protected void BtnSaveClick(object sender, EventArgs e)
        {
            Page.CloseMessage(lblMsg);
            lblMsgCapt.Visible = false;
            if (!Page.IsValid) return;

            lblMsgCapt.Visible = false;
            captCode.ValidateCaptcha(txtCaptText.Text);
            if (!captCode.UserValidated)
            {
                lblMsgCapt.Visible = true;
                return;
            }

            string subjectes = chklSubject.Items.Cast<ListItem>().Where(item => item.Selected).Aggregate(string.Empty, (current, item) => current + (item.Value + ","));
            if (!string.IsNullOrEmpty(subjectes)) subjectes = subjectes.Substring(0, subjectes.Length - 1);
            try
            {
                var studentRequest = new StudentRequest
                {
                    Name = txtName.Text,
                    Address = txtAddress.Text,
                    District = txtDistrict.Text,
                    City = txtCity.Text,
                    Email = txtEmail.Text,
                    Subject = subjectes,
                    Title = txtTitle.Text,
                    Content = txtContent.Text,
                    UpdatedDate = DateTime.Now
                };

                if (!string.IsNullOrEmpty(txtFees.Text)) studentRequest.Fees = Convert.ToDecimal(txtFees.Text);

                StudentRequestServices.SaveOrUpdate(studentRequest);
                //SendEmail(studentRequest);
                SendVerificationEmail(studentRequest);

                ClearInputFields();
                //Page.DisplayMessage(lblMsg, "Bạn đã đăng tin thành công!", MessageType.Success);
                Page.DisplayMessage(lblMsg, "Vui lòng kiểm tra email để kích hoạt tin vừa đăng ký gửi", MessageType.Information);
                //vui lng kiem tra email de kich hoat tin vua dang ky gui
            }
            catch (EmailAlreadyLockException)
            {
                Page.DisplayMessage(lblMsg, string.Format("Email {0} đã bị ban!", txtEmail.Text), MessageType.Error);
            }
            catch (HttpException httpException)
            {
                if (httpException.Message.IndexOf("SMTP server") >= 0)
                {
                    ClearInputFields();
                    //Page.DisplayMessage(lblMsg, "Bạn đã đăng tin thành công!", MessageType.Success);
                    Page.DisplayMessage(lblMsg, "Vui lòng kiểm tra email để kích hoạt tin vừa đăng ký gửi", MessageType.Information);
                }
                else throw;
            }
        }

        protected void BtnCancelClick(object sender, EventArgs e)
        {
            ClearInputFields();
        }

        #region Private Methods
        private void SendEmail(StudentRequest stdRequest)
        {
            IList<Teacher> sbTeachers = TeacherServices.GetSubcribeTeachers(stdRequest.Subject);

            var agrs = new object[] { stdRequest, sbTeachers };
            System.Threading.ThreadPool.QueueUserWorkItem(SendSubcribeEmails, agrs);
        }

        private void SendSubcribeEmails(object state)
        {
            var args = state as object[];

            if (args == null) return;
            var studentRequest = args[0] as StudentRequest;
            IList<Teacher> teachers = args[1] as List<Teacher>;

            SendVerificationEmail(studentRequest);

            // ReSharper disable PossibleNullReferenceException
            string baseMail = "<div style=\"text-align: justify;\">{0}</div><br /><div>";
            baseMail += "<label style=\"font-weight: bold;\"> LƯU Ý:</label><br />";
            baseMail += "Bạn có thể hủy việc đăng ký nhận tin tức mới qua email bấc cứ lúc nào bằng cách nhấp chuột vào đường dẫn dưới đây.<br />";
            baseMail += "<a href=\"{1}\">{1}</a></div>";

            foreach (Teacher teacher in teachers)
            {
                var unSubcribeUrl = string.Format("{0}/unsubscribe.aspx?tchid={1}", SiteUrl, teacher.ID);
                var mailContent = string.Format(baseMail, studentRequest.Content, unSubcribeUrl);

                EmailSender.SendMailAsync(string.Format("Hi!Teachers - {0}", studentRequest.Title), mailContent, teacher.Email);
            }
            // ReSharper restore PossibleNullReferenceException
        }

        private void SendVerificationEmail(StudentRequest request)
        {
            string tmpPath = Server.MapPath("mailtemplates");
            string mailCntPath = Path.Combine(tmpPath, "MailContents.xml");

            var dataSet = new DataSet();
            dataSet.ReadXml(mailCntPath);
            DataRow[] rows = dataSet.Tables["Verification"].Select();
            string subject = Convert.ToString(rows[0]["Subject"]);

            NVelocityBuilder.SetResourcePath(tmpPath);
            string contentMail = NVelocityBuilder.VerificationEmailBuilder(Convert.ToString(rows[0]["Content"]), SiteUrl, request.ID, request.Name);

            EmailSender.SendMail(subject, contentMail, request.Email);
        }

        private void ClearInputFields()
        {
            txtName.Text = string.Empty;
            txtAddress.Text = string.Empty;
            txtDistrict.Text = string.Empty;
            txtCity.Text = string.Empty;
            txtEmail.Text = string.Empty;
            txtTitle.Text = string.Empty;
            txtContent.Text = string.Empty;
            txtFees.Text = string.Empty;
            txtCaptText.Text = string.Empty;
        }
        #endregion
    }
}
